<template>
  <BaseDialog
    v-model:visible="visible"
    title="修改密码"
    icon="Lock"
    width="500px"
    :show-footer="false"
    :close-on-click-modal="false"
    @close="resetForm"
  >
    <div class="change-password-form">
      <!-- 修改密码表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <BaseInput
            v-model="form.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <BaseInput
            v-model="form.newPassword"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="Key"
            size="large"
            show-password
          />
          <div class="password-tips">
            <el-text type="info" size="small">
              密码长度6-20位，必须包含大小写字母和数字
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <BaseInput
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            prefix-icon="Key"
            size="large"
            show-password
          />
        </el-form-item>
      </el-form>

      <!-- 安全提示 -->
      <div class="security-tips">
        <el-alert
          type="warning"
          :closable="false"
          show-icon
        >
          <template #title>
            <div class="security-content">
              <div class="security-title">安全提示</div>
              <ul class="security-list">
                <li>修改密码后需要重新登录</li>
                <li>建议定期更换密码以保障账户安全</li>
                <li>请勿使用过于简单的密码</li>
              </ul>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <BaseButton
          variant="outline"
          size="large"
          @click="visible = false"
        >
          取消
        </BaseButton>
        <BaseButton
          type="primary"
          size="large"
          :loading="loading"
          @click="handleSubmit"
        >
          修改密码
        </BaseButton>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import { Lock, Key } from '@element-plus/icons-vue'
import BaseDialog from '../common/BaseDialog.vue'
import BaseInput from '../common/BaseInput.vue'
import BaseButton from '../common/BaseButton.vue'
import axios from 'axios'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
      message: '密码必须包含大小写字母和数字', 
      trigger: 'blur' 
    },
    {
      validator: (rule, value, callback) => {
        if (value === form.currentPassword) {
          callback(new Error('新密码不能与当前密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    // 二次确认
    await ElMessageBox.confirm(
      '修改密码后需要重新登录，确定要继续吗？',
      '确认修改',
      {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true

    const response = await axios.put('/user/change-password', {
      currentPassword: form.currentPassword,
      newPassword: form.newPassword,
      confirmPassword: form.confirmPassword
    }, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      visible.value = false
      emit('success')
      resetForm()
      
      // 延迟退出登录，给用户看到成功消息的时间
      setTimeout(() => {
        userStore.logout()
      }, 2000)
    } else {
      throw new Error(response.data.message || '修改密码失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('修改密码失败:', error)
      ElMessage.error('修改密码失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}
</script>

<style scoped>
.change-password-form {
  padding: 0;
  max-height: 100%;
  overflow: visible;
}

.password-tips {
  margin-top: var(--spacing-xs);
}

.security-tips {
  margin: var(--spacing-lg) 0;
}

.security-content {
  text-align: left;
}

.security-title {
  font-weight: var(--font-weight-medium);
  margin-bottom: var(--spacing-sm);
  color: var(--color-warning-dark);
}

.security-list {
  margin: 0;
  padding-left: var(--spacing-lg);
  color: var(--color-text-secondary);
}

.security-list li {
  margin-bottom: var(--spacing-xs);
  font-size: var(--font-size-sm);
  line-height: var(--line-height-normal);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  margin-top: var(--spacing-xl);
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  margin-bottom: var(--spacing-sm);
}

:deep(.el-alert) {
  border-radius: var(--radius-md);
  border: 1px solid var(--color-warning-200);
  background: var(--color-warning-50);
}

:deep(.el-alert__icon) {
  color: var(--color-warning);
}

:deep(.el-alert__title) {
  color: var(--color-text-primary);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .form-actions {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .form-actions .base-button {
    width: 100%;
  }
}
</style>
